package com.ljcalc.business.components.fetchers;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URLConnection;
import java.util.List;

import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
import org.cyberneko.html.HTMLConfiguration;

import com.ljcalc.business.components.Combination;
import com.ljcalc.business.components.ConnectionFactory;
import com.ljcalc.business.components.SSLHistoryResultItemListHandler;

public class HistoryResultFetcher extends ContentFetcher {

	List<Combination> list = null;
	
	public HistoryResultFetcher(String url) {
		super(url);
	}

	public int loadContent() throws IOException {
		if(url==null||!goodUrlFormat)
			return 0;
		HistoryResultItemListHandler handler = null;
		if(url.toString().indexOf("svenskaspel")!=-1){
			handler = new SSLHistoryResultItemListHandler();
		}else if(url.toString().indexOf("singaporepools")!=-1){
			handler = new SPTTHistoryResultItemListHandler();
		}
		XMLParserConfiguration xmlReaderParser = new HTMLConfiguration();
		xmlReaderParser.setDocumentHandler(handler);
		URLConnection connection = ConnectionFactory.createURLConnection(url) ;
		connection.connect();
		String encoding = connection.getContentEncoding();
        Reader reader = new InputStreamReader(new BufferedInputStream(url.openStream())); 
		XMLInputSource src = new XMLInputSource(null, null, null, reader, encoding);	  
        //put the map into a centralized content container
		xmlReaderParser.parse(src);
		reader.close();		
		list = handler.getList();
		return list==null?0:list.size();
	}
	
	public List getList(){
		return list;
	}

}
